<script setup lang="ts">
import useCatrgoryStore from "@/store/modules/category";
import { watch, ref, reactive, nextTick } from "vue";
import {
  reqGetAttrInfoList,
  reqAddOrUpdateAttr,
  reqDeleteAttr,
} from "@/api/product/attr";
import type {
  attrListResponseData,
  attrList,
  attr,
  attrValue,
} from "@/api/product/attr/type";
import { ElMessage } from "element-plus";
const categoryStore = useCatrgoryStore();
// 该字段用于存储attrList
let attrList = ref<attrList>([]);
// 该字段用于控制切换场景
let scene = ref<number>(0);
// 新增属性的数据
let attrParams = reactive<attr>({
  attrName: "",
  attrValueList: [],
  categoryId: "",
  categoryLevel: 3,
});
// 该字段用于存储对应的el-input组件实例
let inputArr = ref<any>([]);
// 获取attr列表的函数
const getAttrInfoList = async () => {
  const { c1Id, c2Id, c3Id } = categoryStore;
  // 三级分类id从有到无
  if (!c3Id) {
    // 清空上一次查询的属性与属性值
    return (attrList.value = []);
  }
  // 三级分类id从无到有
  let res: attrListResponseData = await reqGetAttrInfoList(
    c1Id as number,
    c2Id as number,
    c3Id as number
  );
  if (res.code == 200) {
    attrList.value = res.data;
  }
};
// 监视三级分类id
watch(
  () => categoryStore.c3Id,
  () => {
    getAttrInfoList();
  }
);
// 添加属性的事件回调
const addAttr = () => {
  // 清空attrParams中的所有字段,Object.assign(target,source),会返回一个合并过的对象，会改变target原对象
  Object.assign(attrParams, {
    attrName: "",
    attrValueList: [],
    // 收集attrParams的categoryId字段
    categoryId: categoryStore.c3Id,
    categoryLevel: 3,
  });
  scene.value = 1;
};
// 修改属性的事件回调
const updateAttr = (row: attr) => {
  scene.value = 1;
  // 深拷贝attrParams
  Object.assign(attrParams, JSON.parse(JSON.stringify(row)));
};
// 场景1的取消按钮的回调
const cancel = () => {
  scene.value = 0;
};
// 点击添加属性值按钮的回调
const addAttrValue = () => {
  // 向el-table的data字段绑定的数组中追加一个对象
  attrParams.attrValueList.push({ valueName: "", isEdit: true });
  nextTick(() => {
    inputArr.value[attrParams.attrValueList.length - 1].focus();
  });
};
// 点击保存按钮的回调
const save = async () => {
  let res: any = await reqAddOrUpdateAttr(attrParams);
  if (res.code == 200) {
    ElMessage({
      type: "success",
      message: attrParams.id ? "修改属性成功" : "添加属性成功",
    });
    // 重新获取attr数据
    getAttrInfoList();
  } else {
    ElMessage({
      type: "error",
      message: attrParams.id ? "修改属性失败" : "添加属性失败",
    });
  }
  // 切换场景
  scene.value = 0;
};
// input框失去焦点的回调
const toLook = (row: attrValue, $index: number) => {
  // input框绑定的字段的值不能为空
  if (row.valueName.trim() == "") {
    // 删除属性值为空的元素
    attrParams.attrValueList.splice($index, 1);
    return ElMessage({
      type: "error",
      message: "属性值不能为空",
    });
  }
  // input框绑定的字段的值不能重复
  let repeat: any = attrParams.attrValueList.find((item: attrValue) => {
    // 要将当前项从数组中排除出去，否则一定重复
    if (item != row) {
      return item.valueName === row.valueName;
    }
  });
  if (repeat) {
    //将重复的属性值从数组当中剔除掉
    attrParams.attrValueList.splice($index, 1);
    ElMessage({
      type: "error",
      message: "属性值不能重复",
    });
  }
  row.isEdit = false;
};
// 点击div标签的回调
const toEdit = (row: attrValue, $index: number) => {
  row.isEdit = true;
  // 让input框自动获取焦点
  nextTick(() => {
    inputArr.value[$index].focus();
  });
};
// 点击删除attr的按钮回调
const deleteAttr = async (id: number) => {
  let res: any = await reqDeleteAttr(id);
  if (res.code == 200) {
    ElMessage({
      type: "success",
      message: "删除属性成功",
    });
    // 重新获取attrList
    getAttrInfoList();
  } else {
    ElMessage({
      type: "error",
      message: "删除属性失败",
    });
  }
};
// // 该组件即将销毁的生命周期函数钩子
// onBeforeUnmount(() => {
//   // 清空categoryStore的pinia数据
//   categoryStore.$reset();
// });
</script>

<template>
  <div>
    <category :scene="scene" />
    <div>
      <el-card style="margin: 10px 0" v-show="scene == 0">
        <el-button
          type="primary"
          icon="Plus"
          :disabled="categoryStore.c3Id ? false : true"
          @click="addAttr"
          v-have="`btn.Attr.add`"
          >添加属性</el-button
        >
        <el-table border :data="attrList">
          <el-table-column
            label="序号"
            type="index"
            align="center"
            width="80px"
          ></el-table-column>
          <el-table-column
            label="属性名称"
            width="120px"
            prop="attrName"
          ></el-table-column>
          <el-table-column label="属性值名称" width>
            <template v-slot="{ row, $index }">
              <el-tag
                type="success"
                style="margin: 5px"
                v-for="item in row.attrValueList"
                :key="item.id"
                >{{ item.valueName }}</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120px">
            <template v-slot="{ row, $index }">
              <el-button
                size="default"
                icon="Edit"
                @click="updateAttr(row)"
                v-have="`btn.Attr.update`"
              ></el-button>
              <el-popconfirm
                :title="`您确定删除${row.attrName}吗`"
                icon="Delete"
                width="200px"
                @confirm="deleteAttr(row.id)"
              >
                <template #reference>
                  <el-button
                    size="default"
                    icon="Delete"
                    v-have="`btn.Attr.remove`"
                  ></el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <el-card style="margin: 10px 0" v-show="scene == 1">
        <el-form inline>
          <el-form-item label="属性名称">
            <el-input
              placeholder="请输入属性的名称"
              v-model="attrParams.attrName"
            ></el-input>
          </el-form-item>
        </el-form>
        <el-button
          type="primary"
          icon="Plus"
          :disabled="attrParams.attrName ? false : true"
          @click="addAttrValue"
          >添加属性值</el-button
        >
        <el-button @click="cancel">取消</el-button>
        <el-table
          border
          style="margin: 10px 0"
          :data="attrParams.attrValueList"
        >
          <el-table-column
            label="序号"
            type="index"
            align="center"
            width="80px"
          ></el-table-column>
          <el-table-column label="属性值" width>
            <template v-slot="{ row, $index }">
              <el-input
                :ref="(vc: any) => inputArr[$index] = vc"
                v-model="row.valueName"
                v-if="row.isEdit"
                @blur="toLook(row, $index)"
              ></el-input>
              <div v-else @click="toEdit(row, $index)">{{ row.valueName }}</div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width>
            <template v-slot="{ row, $index }">
              <el-button
                type="danger"
                size="default"
                icon="Delete"
                @click="attrParams.attrValueList.splice($index, 1)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button
          type="primary"
          :disabled="
            attrParams.attrValueList.length >= 1 &&
            attrParams.attrValueList[0].valueName.trim()
              ? false
              : true
          "
          @click="save"
          >保存</el-button
        >
        <el-button @click="cancel">取消</el-button>
      </el-card>
    </div>
  </div>
</template>

<style scoped></style>
